package com.onlylemi.mapview.library.layer;


import com.onlylemi.mapview.library.MapView;
import ohos.agp.render.*;
import ohos.agp.utils.Matrix;
import ohos.media.image.PixelMap;
import ohos.multimodalinput.event.TouchEvent;

/**
 * MapLayer
 *
 * @author: onlylemi
 */
public class MapLayer extends MapBaseLayer {

    private static final String TAG = "MapLayer";

    private PixelMap image;

    public MapLayer(MapView mapView) {
        super(mapView);
        level = MAP_LEVEL;
    }

    public void setImage(PixelMap image) {
        this.image = image;
        initMapLayer();
    }

    /**
     * init map image layer
     */
    private void initMapLayer() {
        float zoom = getInitZoom(mapView.getWidth(), mapView.getHeight(), image.getImageInfo().size.width, image
                .getImageInfo().size.height);
        mapView.setCurrentZoom(zoom, 0, 0);

        float width = mapView.getWidth() - zoom * image.getImageInfo().size.width;
        float height = mapView.getHeight() - zoom * image.getImageInfo().size.height;

        mapView.translate(width / 2, height / 2);
    }

    /**
     * calculate init zoom
     *
     * @param viewWidth
     * @param viewHeight
     * @param imageWidth
     * @param imageHeight
     * @return float
     */
    private float getInitZoom(float viewWidth, float viewHeight, float imageWidth,
                              float imageHeight) {
        float widthRatio = viewWidth / imageWidth;
        float heightRatio = viewHeight / imageHeight;

        if (widthRatio * imageHeight <= viewHeight) {
            return widthRatio;
        } else if (heightRatio * imageWidth <= viewWidth) {
            return heightRatio;
        }
        return 0;
    }

    @Override
    public void onTouch(TouchEvent event) {

    }

    @Override
    public void draw(Canvas canvas, Matrix currentMatrix, float currentZoom, float
            currentRotateDegrees) {
        canvas.save();
        canvas.setMatrix(currentMatrix);
        if (image != null) {
            canvas.drawPixelMapHolder(new PixelMapHolder(image), 0, 0, new Paint());
        }
        canvas.restore();
    }

    public PixelMap getImage() {
        return image;
    }
}
